<template>
  <div class="admin-home-container">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>社团管理系统</h2>
          <div class="user-info">
            <span>欢迎，{{ username }}</span>
            <el-button @click="handleLogout">退出登录</el-button>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px">
          <el-menu
            :default-active="activeMenu"
            @select="handleSelect"
            class="admin-menu"
          >
            <el-menu-item index="1">
              <span>社团申请管理</span>
            </el-menu-item>
            <el-menu-item index="2">
              <span>系统设置</span>
            </el-menu-item>
            <el-menu-item index="3">
              <span>数据管理</span>
            </el-menu-item>
            <el-menu-item index="4">
              <span>用户管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main>
          <!-- 社团申请管理 -->
          <div v-if="activeMenu === '1'">
            <h3>社团申请管理</h3>
            <el-table :data="applications.slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%">
              <el-table-column prop="name" label="社团名称" />
              <el-table-column prop="description" label="社团简介" show-overflow-tooltip />
              <el-table-column prop="contact" label="联系方式" />
              <el-table-column prop="location" label="活动场地" />
              <el-table-column prop="createTime" label="申请时间">
                <template #default="scope">
                  {{ new Date(scope.row.createTime).toLocaleString() }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag type="warning" v-if="scope.row.status === 0">待审核</el-tag>
                  <el-tag type="success" v-else-if="scope.row.status === 1">已通过</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.status === 2">已拒绝</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button 
                    type="success" 
                    link 
                    @click="handleApprove(scope.row)"
                    :disabled="scope.row.status !== 0"
                  >通过</el-button>
                  <el-button 
                    type="danger" 
                    link 
                    @click="showRejectDialog(scope.row)"
                    :disabled="scope.row.status !== 0"
                  >拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="applications.length"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
          
          <!-- 系统设置 -->
          <div v-if="activeMenu === '2'">
            <h3>系统设置</h3>
            <el-form :model="systemSettingsFrom" label-width="200px" :append-to-body="true">
              <el-form-item label="社团名称长度" prop="clubNameLengthLimit">
                <el-input-number
                  v-model="systemSettingsFrom.clubNameLengthLimit" 
                  :min="1" 
                  :max="50"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="社团简介长度">
                <el-input-number 
                  v-model="systemSettingsFrom.clubDescriptionLengthLimit" 
                  :min="1" 
                  :max="500"
                />
              </el-form-item>
              <!-- <el-form-item label="每个用户最大社团数">
                <el-input-number 
                  v-model="systemSettings.maxClubsPerUser" 
                  :min="1" 
                  :max="10"
                />
              </el-form-item>
              <el-form-item label="活动审核">
                <el-switch v-model="systemSettings.requireActivityApproval" />
              </el-form-item> -->
              <el-form-item>
                <el-button type="primary" @click="saveSettings">保存设置</el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 数据管理 -->
          <div v-if="activeMenu === '3'">
            <h3>数据管理</h3>
            <el-row :gutter="20" class="mb-4">
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>数据备份</span>
                    </div>
                  </template>
                  <div class="card-content">
                    <p>将系统当前数据导出为备份文件</p>
                    <el-button 
                      type="primary" 
                      @click="handleBackup"
                      :loading="backupLoading"
                    >
                      开始备份
                    </el-button>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card>
                  <template #header>
                    <div class="card-header">
                      <span>数据恢复</span>
                    </div>
                  </template>
                  <div class="card-content">
                    <p>从备份文件恢复系统数据</p>
                    <input
                      type="file"
                      accept=".json"
                      style="display: none"
                      ref="fileInput"
                      @change="handleFileChange"
                    >
                    <el-button 
                      type="warning" 
                      @click="$refs.fileInput.click()"
                      :loading="restoreLoading"
                    >
                      选择备份文件
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 用户管理 -->
          <div v-if="activeMenu === '4'">
            <h3>用户管理</h3>
            <el-table :data="userList" style="width: 100%">
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="realName" label="真实姓名" />
              <el-table-column prop="email" label="邮箱">
                <template #default="scope">
                  <span v-if="scope.row.id !== userId">{{ scope.row.email }}</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="电话">
                <template #default="scope">
                  <span v-if="scope.row.id !== userId">{{ scope.row.phone }}</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button 
                    :type="scope.row.status === 1 ? 'danger' : 'success'"
                    link
                    @click="handleUserStatusChange(scope.row)"
                    :disabled="scope.row.id === userId"
                  >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝申请"
      width="30%"
    >
      <el-form :model="rejectForm" :rules="rejectFormRules">
        <el-form-item label="拒绝原因" prop="rejectReason">
          <el-input
            v-model="rejectForm.rejectReason"
            type="textarea"
            rows="3"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleReject">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Check, Download, Setting } from '@element-plus/icons-vue'
import request from '../utils/request'
import { el } from 'element-plus/es/locales.mjs'

const router = useRouter()
const username = ref(localStorage.getItem('adminUsername') || '--')
const userId = ref(localStorage.getItem('adminId'))
const activeMenu = ref('1')
const userList = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 社团审核相关
const applications = ref([])

const loadClubApplications = async () => {
  try {
    const res = await request({
      url: '/club/pending',
      method: 'get'
    })
    if(res.success===false){
      ElMessage.error(res.message||res.data||'获取社团申请列表失败')
      return
    }
    applications.value = res.data
  } catch (error) {
    ElMessage.error('获取社团申请列表失败：' + (error.response?.data?.message || error.message || '未知错误'))
  }
}

const handleApprove = async (application) => {
  try {
    const res = await request({
      url: `/club/approve/${application.id}`,
      method: 'put'
    })
    if (!res.success) {
      ElMessage.error(res.message|| res.data|| '审核操作失败')
      return
    }
    ElMessage.success('审核通过成功')
    loadClubApplications()
  } catch (error) {
    ElMessage.error(error.message || '审核操作失败')
  }
}

// 拒绝对话框相关
const rejectDialogVisible = ref(false)
const rejectFormRules = {
  rejectReason: [
    { required: true, message: '请输入拒绝原因', trigger: 'blur' },
    { min: 1, max: 200, message: '拒绝原因长度应在1到200个字符之间', trigger: 'blur' }
  ]
}

const rejectForm = reactive({
  id: null,
  rejectReason: ''
})

const showRejectDialog = (application) => {
  rejectForm.id = application.id
  rejectForm.rejectReason = ''
  rejectDialogVisible.value = true
}

const handleReject = async () => {
  if (!rejectForm.rejectReason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  try {
    const res = await request({
      url: `/club/reject/${rejectForm.id}?rejectReason=${rejectForm.rejectReason}`,
      method: 'put',
      data: {
        rejectReason: rejectForm.rejectReason
      }
    })
    if (!res.success) {
      ElMessage.error(res.message|| res.data|| '拒绝操作失败')
      return
    }
    ElMessage.success('拒绝申请成功')
    rejectDialogVisible.value = false
    loadClubApplications()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || error.message || '审核操作失败')
  }
}

// 数据管理相关
const backupLoading = ref(false)
const restoreLoading = ref(false)

const handleBackup = async () => {
  if (backupLoading.value) return
  backupLoading.value = true
  try {
    const res = await request({
      url: '/system/backup',
      method: 'post',
      responseType: 'blob',
      headers: {
        Accept: 'application/json, application/octet-stream'
      }
    })
    
    // 检查响应类型
    const contentType = res.headers?.['content-type'] || ''
    if (contentType.includes('application/json')) {
      // 如果是JSON格式，说明可能是错误信息
      const text = await res.text()
      try {
        const result = JSON.parse(text)
        ElMessage.error(result.message || '备份失败')
      } catch {
        ElMessage.error('备份失败：服务器返回了无效的数据格式')
      }
      return
    }
    
    // 生成文件名
    const now = new Date()
    const dateStr = now.toISOString().split('T')[0]
    const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '-')
    const defaultFileName = `club_system_backup_${dateStr}_${timeStr}.json`
    
    // 创建Blob对象
    const blob = new Blob([res], { type: contentType })
    
    try {
      // 使用showSaveFilePicker API让用户选择保存位置
      const handle = await window.showSaveFilePicker({
        suggestedName: defaultFileName,
        types: [{
          description: '备份文件',
          accept: { 'application/json': ['.json'] }
        }]
      })
      
      // 写入文件
      const writable = await handle.createWritable()
      await writable.write(blob)
      await writable.close()
      
      ElMessage.success('数据备份成功')
    } catch (error) {
      if (error.name !== 'AbortError') {
        // 如果不是用户取消操作，则使用传统下载方式作为备选
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = defaultFileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('数据备份成功')
      }
    }
  } catch (error) {
    console.error('备份失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '未知错误'
    ElMessage.error('数据备份失败：' + errorMessage)
  } finally {
    backupLoading.value = false
  }
}

const handleRestore = async (file) => {
  if (restoreLoading.value) return
  if (!file) {
    ElMessage.warning('请选择备份文件')
    return
  }
  
  restoreLoading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await request({
      url: '/system/restore',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    if(!res.success){
      ElMessage.error(res.message||res.data||'数据恢复失败')
      return
    }
    ElMessage.success('数据恢复成功')
    // 恢复成功后刷新页面
    setTimeout(() => {
      window.location.reload()
    }, 1500)
  } catch (error) {
    console.error('恢复失败:', error)
    ElMessage.error('数据恢复失败：' + (error.message || '请检查备份文件格式是否正确'))
  } finally {
    restoreLoading.value = false
  }
}

const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    handleRestore(file)
  }
}


// 系统设置相关
const systemSettings = ref({
  clubNameLengthLimit: 20,
  clubDescriptionLengthLimit: 100,
  // maxClubsPerUser: 3,
  // requireActivityApproval: true
})

const loadSettings = async () => {
  try {
    const res = await request({
      url: '/system/get-system-config',
      method: 'get'
    })
    if(!res.success){
      ElMessage.error(res.message)
      return
    }
    systemSettings.value = JSON.parse(res.data)
    systemSettingsFrom.clubNameLengthLimit = systemSettings.value.clubNameLengthLimit
    systemSettingsFrom.clubDescriptionLengthLimit = systemSettings.value.clubDescriptionLengthLimit
    console.log(systemSettingsFrom.clubNameLengthLimit, systemSettingsFrom.clubDescriptionLengthLimit)
  } catch (error) {
    ElMessage.error('获取系统设置失败')
  }
}

const systemSettingsFrom = reactive({
  clubNameLengthLimit: 20,
  clubDescriptionLengthLimit: 100
})

const saveSettings = async () => {
  const p1 = systemSettingsFrom.clubNameLengthLimit
  const p2 = systemSettingsFrom.clubDescriptionLengthLimit
  try {
    const res = await request({
      url: `/system/update-system-config?clubNameLengthLimit=${p1}&clubDescriptionLengthLimit=${p2}`,
      method: 'post'
    })
    if(!res.success){
      ElMessage.error(res.message||res.data||'保存设置失败')
      return
    }
    ElMessage.success('保存设置成功')
    // 重新加载系统设置
    loadSettings()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || error.message || '保存设置失败')
  }
}

// 通用方法
const handleSelect = (index) => {
  activeMenu.value = index
  if (index === '4') {
    loadUserList()
  }
}

// 用户管理相关
const loadUserList = async () => {
  try {
    const res = await request({
      url: '/system/all-user',
      method: 'get'
    })
    if (!res.success) {
      ElMessage.error(res.message || res.data || '获取用户列表失败')
      return
    }
    userList.value = res.data
        .filter(user => parseInt(user.id) !==parseInt( userId.value))
  } catch (error) {
    ElMessage.error('获取用户列表失败：' + (error.response?.data?.message || error.message || '未知错误'))
  }
}

const handleUserStatusChange = async (user) => {
  try {
    const res = await request({
      url: '/system/modify-user',
      method: 'put',
      data: {
        id: user.id,
        status: user.status === 1 ? 0 : 1
      }
    })
    if (!res.success) {
      ElMessage.error(res.message || res.data || '修改用户状态失败')
      return
    }
    ElMessage.success('修改用户状态成功')
    loadUserList()
  } catch (error) {
    ElMessage.error('修改用户状态失败：' + (error.response?.data?.message || error.message || '未知错误'))
  }
}

const handleLogout = async () => {
  try {
    const res = await request({
      url: '/auth/logout',
      method: 'post'
    })
    
    if (res.success) {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      ElMessage.success('退出成功')
      router.push('/admin/login')
    }
  } catch (error) {
    ElMessage.error(error.message || '退出失败')
  }
}

const checkAdminIdentity = async () => {
  try {
    const res = await request({
      url: '/auth/info',
      method: 'get'
    })
    if (!res.success || !res.data || res.data.id != localStorage.getItem('adminId')) {
      ElMessage.error('666登录信息已失效，请重新登录...')
      setTimeout(() => {
        router.push('/admin/login')
      }, 25000) // 停留一坤秒
      return false
    }
    return true
  } catch (error) {
    ElMessage.error('666身份验证失败，请重新登录：' + (error.response?.data?.message || error.message || '未知错误'))
    setTimeout(() => {
        router.push('/admin/login')
      }, 2500) // 停留一坤秒
      return false
  }
}

let intervalId = null

onMounted(() => {
  checkAdminIdentity().then(valid => {
    if (valid) {
      loadClubApplications()
      loadSettings()
    }
  })
  intervalId = setInterval(() => {
    checkAdminIdentity().then(valid => {
    if (valid) {
      loadClubApplications()
      loadSettings()
    }
  })
  }, 25000) // 每十坤秒检查一次
})
onBeforeUnmount(() => {
  clearInterval(intervalId) // 离开页面时清除定时器，避免内存泄漏
})
</script>

<style scoped>
.admin-home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-container {
  height: 100%;
  overflow: hidden;
}

.el-header {
  background-color: #67C23A;
  padding: 0 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.header-content {
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info span {
  color: #fff;
  font-size: 15px;
  font-weight: 500;
}

.user-info .el-button {
  padding: 10px 20px;
  font-size: 14px;
  color: #f56c6c;
  transition: all 0.3s ease;
  border-radius: 4px;
}

.user-info .el-button:hover {
  color: #fff;
  background-color: #f56c6c;
  transform: translateY(-1px);
}

.header-content h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

.el-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  width: 220px !important;
}

.el-menu-vertical {
  border-right: none;
  padding: 12px 0;
}

.el-menu-item {
  height: 50px;
  line-height: 50px;
  margin: 4px 0;
  padding: 0 24px !important;
}

.el-menu-item:hover {
  background-color: #f0f7ff;
}

.el-main {
  background-color: #f5f7fa;
  padding: 24px;
  overflow-y: auto;
  height: calc(100vh - 64px);
}

.main-content {
  padding: 0;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.data-management {
  margin-top: 24px;
}

.box-card {
  height: 100%;
  min-height: 200px;
}

.card-content {
  text-align: center;
  padding: 32px 24px;
}

.card-content p {
  margin-bottom: 24px;
  color: #606266;
  font-size: 15px;
}

.upload-demo {
  text-align: center;
}

.el-table {
  margin-top: 16px;
  border-radius: 4px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
  padding: 12px 0;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-button--text {
  padding: 4px 8px;
  font-size: 14px;
}

.el-button--primary {
  padding: 10px 24px;
  font-size: 14px;
  height: 40px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>